import {BrowserWindow, app, ipcMain, dialog} from 'electron'
import {join} from 'path'
import {ElectronChannel} from './types/ipc'

const onReady = (type: string) => {
  app.whenReady().then(() => {
    const mainWindow = createWindow(type)
    mainWindowListens(mainWindow)
  })
}

const mainWindowListens = (mainWindow: BrowserWindow) => {
  ipcMainHandles(mainWindow)
  ipcMainOnS(mainWindow)
}

const ipcMainOnS = (mainWindow: BrowserWindow) => {
}

const ipcMainHandles = (mainWindow: BrowserWindow) => {
  ipcMain.handle(ElectronChannel.openDialog, () => {
    dialog.showOpenDialog(mainWindow).then(v => {
      console.log(v)
    })
  })
}

const createWindow = (type = 'dev') => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true, //允许在渲染进程中直接使用 Node.js API
      contextIsolation: true, //启用上下文隔 (提高安全性)
      preload: join(__dirname, 'preload.js')
    }
  })
  if (type === 'dev') {
    win.loadURL('http://localhost:6789/start')
    win.webContents.openDevTools()
  } else if (type === 'prod') {
    const path = join(__dirname, 'dist', 'index.html')
    win.loadFile(path)
  }
  return win
}

const appListens = () => {
  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin')
      app.quit()
  })
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0)
      createWindow()
  })
}


export const main = () => {
  onReady(process.env.NODE_ENV || 'dev');
  appListens()
}